# -*- coding: utf-8 -*-

# 给定一个链表，旋转链表，将链表每个节点向右移动 k 个位置，其中 k 是非负数

# 示例 1:
# 输入: 1->2->3->4->5->NULL, k = 2
# 输出: 4->5->1->2->3->NULL
# 解释:
# 向右旋转 1 步: 5->1->2->3->4->NULL
# 向右旋转 2 步: 4->5->1->2->3->NULL

# 示例 2:
# 输入: 0->1->2->NULL, k = 4
# 输出: 2->0->1->NULL
# 解释:
# 向右旋转 1 步: 2->0->1->NULL
# 向右旋转 2 步: 1->2->0->NULL
# 向右旋转 3 步: 0->1->2->NULL
# 向右旋转 4 步: 2->0->1->NULL

# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

def build_list(param):
    if not param:
        return None;
    rtn = ListNode(param[0]);

    node = rtn;
    for i in range(1, len(param)):
        node.next = ListNode(param[i]);
        node = node.next;

    return rtn;

def print_list(head):
    log = "";
    node = head;
    while node:
        log += str(node.val) + " ";
        node = node.next;
    print log;

class Solution(object):
    def rotateRight(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        if not head:
            return head;

        length = 1;
        last = head;
        while last.next:
            length += 1;
            last = last.next;

        k = length - k % length;
        node = head;

        for i in range(k - 1):
            node = node.next;

        last.next = head;
        head = node.next;
        node.next = None;

        return head;


t = Solution();

head = build_list([0]);
print_list( t.rotateRight(head, 4) );